var fileSystemObject = new ActiveXObject("Scripting.FileSystemObject");
var adoStream;

//扫描仪操作
var Microtek_6240S = {
		"path":function(){
			/*
			try{
				var $t5c6I1v2 = $q3z8q5k7p4j5.GetFolder("C:\\Midocumenter\\Microtek");
				return "C:\\Midocumenter\\Microtek";
			}catch(ex){
				//兼容之前安装的路径
				return "D:\\MICROTEK-6240s";
			}
			*/
			return "D:\\MICROTEK-6240s";
		},
		"config":function(){
			return this.path()+"\\ScannerCtrl.ini";
		},
		"open":function(){
			var scaner = ScanOcx;
			
			var cookieMD = getFromCookie("MediDocumenter")
			if(cookieMD=='Microtek_S8090' || cookieMD=='Microtek_S8090_RGB'){
				scaner.DSMode(8);//
			}else if(cookieMD=='Microtek_6240S_NEW'){
				scaner.DSMode(9);// SW_BIO
			}else{
				scaner.DSMode(0);//
			}	
	        
	        var code = scaner.openScanner();
	        
	      /*  if (1 == code){
				Scan.scanerStart = true;
			}else{
				Scan.scanerStart = false;
			}*/
			
			scaner.SetImageName(getMrDocLocalPath(), "0", 1, 7);
			
			scaner.BlackBorderRemoval(1);// 注释：默认黑边补白
			
			if(Scan.getFromCookieMD == "Microtek_MEDI-XT3500" || Scan.getFromCookieMD == 
				"Microtek_MEDI1000" || Scan.getFromCookieMD == "Microtek_MEDI1000_NEW" || 
				Scan.getFromCookieMD == "Microtek_6240S" || Scan.getFromCookieMD == "Microtek_6240S_NEW"){
				// 注释：add at 2015-12-09，否则上传bmp格式太大，上传不了
				scaner.ImageFormat = 2;//jpg  0 bmp 2 tif 3 multitif 4 pdf 5 multipdf
				//scaner.CompressionRate = 20;//注释：压缩质量
				scaner.TiffCompressType = 1; //注释：Tiff压缩  1 JPG压缩  2 G4压缩
				//1：jpeg压缩（可以设置CompressionRate改变jpeg压缩的Tiff图像的压缩率，只针对GRAY 和RGB图像）
				//2：Group4 FAX 压缩（只针对BW图像）。
				
				if(Scan.getFromCookieMD == "Microtek_6240S_NEW" || Scan.getFromCookieMD == "Microtek_MEDI1000_NEW"){
					scaner.SetScanThreshold(50);//注释：黑白阈值 浅 10 <-- 130 --> 250 深  默认128
				}else if(Scan.getFromCookieMD == "Microtek_6240S_DEEP"){
					scaner.SetScanThreshold(30);//注释：黑白阈值 浅 10 <-- 130 --> 250 深  默认128
				}else{
					scaner.SetScanThreshold(130);//注释：黑白阈值 浅 10 <-- 130 --> 250 深  默认128
				}
			}
			// ["0","平板"],
			// ["1","ADF单面"],
			// ["2","ADF双面"]
			if(Scan.getFromCookieMD == "Microtek_S8090_RGB"){// 注释：彩色单页扫，jpg格式存储小，tif格式上传不了
//				scaner.SetScanSourceType(1);
				scaner.ImageFormat = 1;//jpg
				scaner.CompressionRate = 20;//
			}else if(Scan.getFromCookieMD == "Microtek_S8090"){
//				scaner.SetScanSourceType(2);
				scaner.ImageFormat = 2;//tif
				scaner.TiffCompressType = 2;
			}else if(Scan.getFromCookieMD == "Microtek_6240S_NEW"){
				scaner.ScanSourceType = 2;
			}else if(Scan.getFromCookieMD == "Microtek_6240S" || Scan.getFromCookieMD == "Microtek_6240S_DEEP"){
				scaner.SetScanImageLayout(0,0,9.39,12.69);//A4
			}
			
			return code;
		},
		"close":function(){
			var scaner = ScanOcx;
			scaner.CancelXfers();
			scaner.CloseScanner();
		},
		"cancel":function(){
			ScanOcx.CancelXfers();
			alert("本次扫描已中止。");
		},
		"clsid":function(){
			return "<object classid=\"clsid:49903B72-9F44-41E1-A79B-B85A8BCEB89A\"" +
	    		" id=\"ScanOcx\" width=\"0\" height=\"0\"></object>";
	    		/*
	    		"<script for=\"ScanOcx\" event=\"PostScanEveryPage()\">"+
	    			"try{alert(ScanOcx.PostScanEveryPage);Scan.Microtek_6240S.startScan();}catch(ex){" +
						"if (\"49457432-9\" == hosid){alert(\"PostScanEveryPage error\"+ex);}" +
					"}"+
				"</script>";
				*/
				/*
				"<script  LANGUAGE=\"Javascript\" FOR=\"ScanOcx\" EVENT=\"PostAcquire(bSuccess)\" defer=\"defer\">"+
					//"try{Scan.Microtek_6240S.update_abandon();}catch(ex){" +
					//"alert(\"PostAcquire error\");" +
					//"}"+
					"alert('PostAcquire');"+
				"</script>";
				*/
		},
		"scans":function(){
			var scaner = ScanOcx;
			
			scaner.Scan(-1,0);// 连扫
		
			return "scanerReturnValue";
		},
		"scan":function(){
			var scaner = ScanOcx;
			
			scaner.Scan(1,0);// 单扫
			
			return "scanerReturnValue";
		},
		"update_abandon":function(){
			//this.update();
		},
		"startScan":function(bSuccess){
			///*
			if (bSuccess == 1){
				this.update();
			}else{
				ScanOcx.CancelXfers();
				alert("错误代码："+ScanOcx.GetErrorCode()+"\r\n此页文件扫描未成功，请重新扫描！");
			}
			//*/
			/*
			this.update();
			*/
		},
		"update":function(){
			var scaner = ScanOcx;
			var imagePath = scaner.GetCurrentScanImagePath();
	  		if (isUse(imagePath)){
				var map = uploading(imagePath);
				uploadImage(map);
	  		}
		}
};

//开启扫描仪
function openScanerSettings(){
	var scaner = ScanOcx;
//	Microtek_6240S.open();
	
	var cookieMD = 'Microtek_S8090';
	//var cookieMD = getFromCookie("MediDocumenter")
	if(cookieMD=='Microtek_S8090' || cookieMD=='Microtek_S8090_RGB'){
		scaner.DSMode(8);//
	}else if(cookieMD=='Microtek_6240S_NEW'){
		scaner.DSMode(9);// SW_BIO
	}else{
		scaner.DSMode(0);//
	}	
	//scaner.DSMode(8);//
	scaner.openScanner();
    
	if(scaner.GetCapShowUISettings()==0){
		alert("此款扫描仪不支持打开本地界面，请从扫描仪设置！");
	}
	scaner.ShowUISettings();
}

//获取cookie
function getFromCookie(c_name){
	if (document.cookie.length > 0){
		c_start=document.cookie.indexOf(c_name + "=");//通过String对象的indexOf()来检查这个cookie是否存在，不存在就为 -1　　
　　　　　　if (c_start!=-1){ 
　　　　　　　　c_start=c_start + c_name.length+1;//最后这个+1其实就是表示"="号啦，这样就获取到了cookie值的开始位置
　　　　　　　　c_end=document.cookie.indexOf(";",c_start);//其实我刚看见indexOf()第二个参数的时候猛然有点晕，后来想起来表示指定的开始索引的位置...这句是为了得到值的结束位置。因为需要考虑是否是最后一项，所以通过";"号是否存在来判断
　　　　　　　　if (c_end==-1) c_end=document.cookie.length;
　　　　　　　　return unescape(document.cookie.substring(c_start,c_end));//通过substring()得到了值。想了解unescape()得先知道escape()是做什么的，都是很重要的基础，想了解的可以搜索下，在文章结尾处也会进行讲解cookie编码细节
　　　　　　} 
	}
	return "";
}

//设置cookie
function setCookie(c_name, value, expiredays){
	var exdate=new Date();
	exdate.setDate(exdate.getDate() + expiredays);
	document.cookie=c_name+ "=" + escape(value) + ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

//判断是否为空
function isUseful(str){
	if (str == null || str.length == 0 || "null" == str || "undefined" == str){
		return false;
	}
	return true;
}


function isUse(str){
	return isUseful(str);
}

//图片临时存放路径
function getMrDocLocalPath(){
	return "D:\\MrDocLocal";
}



//删除图片临时文件信息
function deleteTempFiles(param){
	try{
		if ("all" == param){
			var $f = fileSystemObject.GetFolder(getMrDocLocalPath());
			var enumFiles = new Enumerator($f.files);
			for (; !enumFiles.atEnd(); enumFiles.moveNext()){
				enumFiles.item().Delete();
			}
		}
	}catch(ex){
		
	}
}

//开启扫描仪
function getScanerOpenInfo(){

	
	var initScanReturnValue = Microtek_6240S.open();;

	
	return initScanReturnValue;
}


function scanerSaomiao($u5q6k3u5d1){
	
	//删除临时文件目录
	deleteTempFiles("all");
	
	//开启扫描仪
	getScanerOpenInfo();
	
	//注释：此处可能是调用扫描仪扫描
	var map = Microtek_6240S.scan();
	
};

function scanerSaomiaos($u5q6k3u5d1){
	//删除临时文件夹路径
	deleteTempFiles("all");

	//开启扫描
	getScanerOpenInfo();
	
	var map = "";
	if(Scan.getFromCookieMD == "Microtek_6240S"){
		map = Microtek_6240S.scans();
	}else{
		map = Microtek_6240S.scans();
	}
	
}

//获取XmlHttpRequest
function getXMLHttpRequest(){
	var XMLHttpRequest = null;
	if (typeof ActiveXObject != "undefined") {
		var aVersions = ["Microsoft.XMLHTTP", "Msxml2.XMLHttp.6.0", "Msxml2.XMLHttp.5.0", "Msxml2.XMLHttp.4.0", "Msxml2.XMLHttp.3.0"];
		for (var i = 0; i < aVersions.length; i++) {
			try {XMLHttpRequest = new ActiveXObject(aVersions[i]);}catch (ex) {}//注释：不能alert循环的创建的
		}
	} else if (typeof XMLHttpRequest != "undefined"){
		XMLHttpRequest = new XMLHttpRequest();
	}
	
	return XMLHttpRequest;
}


function uploading(imagePath){
	var path=$("#path").val();
	var orgCode=$("#orgCode").val();
	var ramdomNum=$("#folderName").val();
	
	adoStream = new ActiveXObject("ADODB.Stream");
	adoStream.Mode = 3;//read write
	
	adoStream.Open();
	adoStream.Type = 1;
   	
   	var filetype = imagePath.substring(imagePath.lastIndexOf(".")+1);
   	var upOneURL = path+"/static/scan/workboard/scaner/upOne.jsp";
   	adohttp = getXMLHttpRequest();
   	adohttp.open('post', upOneURL, false);
   	adohttp.setRequestHeader('-orgCode',orgCode);
   	adohttp.setRequestHeader('-randomNum',ramdomNum);
   	adohttp.setRequestHeader('-fileType',filetype);
	/*adohttp.setRequestHeader('-mrId',Scan.CurrentMrId);//Scan.MrId
	
	
	adohttp.setRequestHeader('-pageOneLocalPath',imagePath.replace(/\\/g,"/"));*/
   	adohttp.setRequestHeader('Content-Type', 'application/x- www-form-urlencoded');

   	
	adoStream.LoadFromFile(imagePath);
	
	
	var fileSize = fileSystemObject.GetFile(imagePath).Size;
	var adoStreamSize = adoStream.Size;
	
   	if (fileSize != adoStreamSize || fileSize < 3584 || adoStreamSize < 3584){
   		adoStream.Close();////
   		adoStream = null;
   		adohttp = null;
   		return "noUp";
   	}
	
	adohttp.setRequestHeader("Content-Length",adoStream.Size);
	
   	adohttp.send(adoStream.Read(adoStream.Size));
   	
   	var map = JSON.parse(adohttp.responseText);
   	
   	
   	
   	adoStream.Close();////
   	adoStream = null;
   	
   	adohttp = null;
   	
   	return map;
}


function uploadImage(map){
	if ("noUp" == map || "noUp" == map.SUCCESS){
		return;
	}
	else if ("0" == map.SUCCESS){

		return;
	}

	
	var filename = map.filename;
	var randomNum=map.randomNum;
	var path=$("#path").val();
	if ("appendOne".indexOf("appendOne") == 0){
		$.ajax({
			type:"post",
			url:path+"/scan/appendOne",
			data:{fileName:filename,randomNum:randomNum},
			success:function(data){
				if(data!=null){
					var html="";
					html+="<li>"+
                          "  <a class='imgActive' href='#'><img src='"+data.url+"' alt=''/></a>"+
                          "  <p>扫描人:&nbsp;&nbsp;"+data.name+"&nbsp;&nbsp;&nbsp;</p>"+
                          "</li>";
					$("#MrDocViewOrBoardUl").append(html);
				}
			}
		});
		
	}
}